package com.suray.rgv.son.data;

import com.suray.basic.wcs.utils.typedef.Byte;
import com.suray.basic.wcs.utils.typedef.Word;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ModbusWriteMessage {

    private Map<MessageInfo, ModbusWriteMsg> messageMap = new HashMap();

    public ModbusWriteMsg setMessageInfo(int startAddress, int data[]) {
        MessageInfo messageInfo = new MessageInfo(startAddress, data.length);
        ModbusWriteMsg writeMsg = messageMap.get(messageInfo);
        if (writeMsg == null) {
            writeMsg = new ModbusWriteMsg(messageInfo.startAddress, messageInfo.dataLength);
        }

        for (int i = 0; i < data.length; i++) {
            String name = "data" + i;
            writeMsg.setValue(name, data[i]);
        }

        return writeMsg;
    }

    class MessageInfo {
        int startAddress;
        int dataLength;
        MessageInfo(int startAddress, int dataLength) {
            this.startAddress = startAddress;
            this.dataLength = dataLength;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            MessageInfo that = (MessageInfo) o;
            return startAddress == that.startAddress &&
                    dataLength == that.dataLength;
        }

        @Override
        public int hashCode() {
            return Objects.hash(startAddress, dataLength);
        }
    }

    public class ModbusWriteMsg extends ModbusBaseMessage {
        ModbusWriteMsg(int startAddress, int dataLength) {
            super("子车modbus写", true);

            baseDatas.add(new Byte("slaveAddr", "从机地址"));
            baseDatas.add(new Byte("funcCode", "功能代码"));
            baseDatas.add(new Word("startAddr", "数据起始地址"));
            baseDatas.add(new Word("dataLength", "寄存器个数"));
            baseDatas.add(new Byte("dataByteNum", "寄存器对应的字节数量"));

            setValue("slaveAddr", 1);
            setValue("funcCode", 0x10);

            setValue("startAddr", startAddress);
            setValue("dataLength", dataLength);
            setValue("dataByteNum", dataLength * 2);

            for (int i = 0; i < dataLength; i++) {
                String name = "data" + i;
                baseDatas.add(new Word(name, "数据"));
            }

            baseDatas.add(new Word("crc", "crc校验"));
        }

        public int getSlaveAddr() {
            return getValue("slaveAddr");
        }

        public int getStartAddr() {
            return getValue("startAddr");
        }

        public int getDataLength() {
            return getValue("dataLength");
        }

        public int getCrc() {
            return getValue("crc");
        }

        @Override
        public byte[] makeMessage() {
            setValue("crc", calcCrc(super.makeMessage()));
            return super.makeMessage();
        }
    }
}
